using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web;
using System.Collections;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using Org.Eurekaa.DNJ.Config;

namespace Org.Eurekaa.DNJ.Helpers
{
    public static class PageHelper
    {
        private const string JQSCRIPT_ID = "__jqScriptBlock__";
        private const string DNJHEADER_ID = "__DNJ_HDR_Block__";
        private const string JQSCRIPT_INIT = "/*[DNJ]*/$(function() {});/*[/DNJ]*/";
        private static bool FirstLoad = true;


        private static LiteralControl jqStart = new LiteralControl(Environment.NewLine + "$(function() {" + Environment.NewLine);
        private static LiteralControl jqEnd = new LiteralControl("});" + Environment.NewLine);
        private static HtmlGenericControl jqScript = new HtmlGenericControl("script");
        private static PlaceHolder jqScriptBody = new PlaceHolder();
        private static Hashtable plugins = new Hashtable();

        private static HtmlGenericControl dnjHdrBlock = null;
        private static List<string> dnjLoadedResources = new List<string>();
        public static void AppendJQueryScript(string script, HtmlHead htmlHeader)
        {            
            if (string.IsNullOrEmpty(script)) return;
            string BASE_URL = HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            HtmlGenericControl jqScriptBlock = (htmlHeader.FindControl(JQSCRIPT_ID) as HtmlGenericControl);
            if (jqScriptBlock == null)
            {
                jqScriptBlock = new HtmlGenericControl("script");
                jqScriptBlock.ID = JQSCRIPT_ID;
                jqScriptBlock.Attributes.Add("type", "text/javascript");

                Literal scriptText = new Literal();
                scriptText.Text = JQSCRIPT_INIT;

                jqScriptBlock.Controls.Add(scriptText);
            }
            (jqScriptBlock.Controls[0] as Literal).Text = (jqScriptBlock.Controls[0] as Literal).Text.Replace("});/*[/DNJ]*/", Environment.NewLine + script + Environment.NewLine + "});/*[/DNJ]*/");


            htmlHeader.Controls.Add(jqScriptBlock);
        }
                
        public static void AppendJQueryPlugin(string selector, string pluginName, string settings, HtmlHead htmlHeader)
        {

            if (!jqScript.Controls.Contains(jqStart)) jqScript.Controls.Add(jqStart);
            if (!jqScript.Controls.Contains(jqScriptBody)) jqScript.Controls.Add(jqScriptBody);
            if (!jqScript.Controls.Contains(jqEnd)) jqScript.Controls.Add(jqEnd);
            jqScript.Attributes.Add("type", "text/javascript");            

//            AppendJQueryScript("$('" + selector + "')." + pluginName + "(" + settings + ");", htmlHeader);
            string pluginKeyName = CryptoHelper.MD5String(selector + pluginName);

            string pluginText = "$('" + selector + "')." + pluginName + "(" + settings + ");" + Environment.NewLine;
            if (plugins[pluginKeyName] != null) (plugins[pluginKeyName] as LiteralControl).Text = pluginText;
            else
            {
                LiteralControl pluginScript = new LiteralControl(pluginText);
                pluginScript.ID = pluginKeyName;
                plugins[pluginKeyName] = pluginScript;
            }
                                            
            foreach (LiteralControl pluginLt in plugins.Values)
                    jqScriptBody.Controls.Add(pluginLt);
            htmlHeader.Controls.Add(jqScript);


            PageHelper.RegisterDNJResource("ui", htmlHeader);

            


            //string jqpScript = "$('" + selector + "')." + pluginName + "(" + settings + ");";
            //string BASE_URL = HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            //HtmlGenericControl jqScriptBlock = (htmlHeader.FindControl(JQSCRIPT_ID) as HtmlGenericControl);
            //Literal scriptText;
            //if (jqScriptBlock == null)
            //{
            //    jqScriptBlock = new HtmlGenericControl("script");
            //    jqScriptBlock.ID = JQSCRIPT_ID;
            //    jqScriptBlock.Attributes.Add("type", "text/javascript");

            //    scriptText = new Literal();
            //    scriptText.ID = "Script_" + JQSCRIPT_ID;
            //    scriptText.Text = JQSCRIPT_INIT;

            //    jqScriptBlock.Controls.Add(scriptText);
            //}
            //scriptText = (jqScriptBlock.Controls[0] as Literal);
            //scriptText.Text = (jqScriptBlock.Controls[0] as Literal).Text.Replace("});/*[/DNJ]*/", Environment.NewLine + jqpScript + Environment.NewLine + "});/*[/DNJ]*/");


            //htmlHeader.Controls.Add(jqScriptBlock);

            //// + 
            //string regExp = @"\$\('" + selector + @"'\)\." + pluginName + @"\(" + @"({(.|\s)*?})" + @"\);";

            //MatchCollection jqmc = Regex.Matches(scriptText.Text, regExp, 
            //    RegexOptions.Compiled | RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline);

            //String oldScript = (jqScriptBlock.Controls[0] as Literal).Text;
            //scriptText.Text = Regex.Replace(scriptText.Text, regExp, jqpScript, RegexOptions.Compiled | RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline);
            //if (jqmc.Count <= 0)
            //{
            //    scriptText.Text = scriptText.Text.Replace("});/*[/DNJ]*/", Environment.NewLine + jqpScript + Environment.NewLine + "});/*[/DNJ]*/");
            //}            
        }

        public static void RegisterDNJResource(string resourceName, HtmlHead htmlHeader)
        {
            
            if (string.IsNullOrEmpty(resourceName)) return;


            string BASE_URL = HttpContext.Current.Request.ApplicationPath.TrimEnd('/');

            if (dnjHdrBlock == null) // try to find it
            {
                foreach (Control c in htmlHeader.Controls)
                {
                    if (c is LiteralControl)
                    {
                        LiteralControl litteral = c as LiteralControl;
                        if (litteral.Text.Contains("src=\"DNJResources.axd?load="))
                        {
                            //litteral.Text = "<!-- removed -->";
                            htmlHeader.Controls.Remove(litteral);
                            break;
                        }
                    }

                    if (c is HtmlGenericControl)
                    {
                        HtmlGenericControl htmlCtl = c as HtmlGenericControl;
                        if (htmlCtl.TagName.ToLower() == "script" && htmlCtl.Attributes["src"] != null && htmlCtl.Attributes["src"].StartsWith("DNJResources.axd?load="))
                        {
                            dnjHdrBlock = htmlCtl;
                            break;
                        }
                        else continue;
                    }

                }
            }

            //Testing for next version 0.4.1
            //ResourcesConfig.LoadConfig("Org.Eurekaa.DNJ", "Resources.ResourceConfig.xml");
            //ResourcesConfig.LoadConfig("Org.Eurekaa.DNJ.UI", "Resources.ResourceConfig.xml");
            //ResourcesConfig.LoadConfig("Org.Eurekaa.DNJ.Ext", "Resources.ResourceConfig.xml");
            //string srcStr = ResourcesConfig.GetResourceString();

            
            if (dnjHdrBlock == null)
            {
                dnjHdrBlock = new HtmlGenericControl("script");
                dnjHdrBlock.ID = DNJHEADER_ID;
                dnjHdrBlock.Attributes.Add("type", "text/javascript");
                dnjHdrBlock.Attributes.Add("src", "DNJResources.axd?load=jquery,cookie,ui[all],fx[all]");
            }
            string srcStr = dnjHdrBlock.Attributes["src"];


            if (dnjLoadedResources.Contains(resourceName)) resourceName = "";
            else
            {
                dnjLoadedResources.Add(resourceName);                
                resourceName = "," + resourceName;
            }
            srcStr += resourceName;
            //string src = dnjHdrBlock.Attributes["src"] + resourceName;
            dnjHdrBlock.Attributes.Add("src", srcStr);

            
            
            htmlHeader.Controls.AddAt(1, dnjHdrBlock);


            
        }
        public static void RegisterHeaderScript(string scriptUrl, HtmlHead htmlHeader)
        {
            string BASE_URL = HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            HtmlGenericControl Include = new HtmlGenericControl("script");
            Include.Attributes.Add("type", "text/javascript");
            Include.Attributes.Add("src", BASE_URL + scriptUrl);
            htmlHeader.Controls.Add(Include);
        }
        public static void RegisterHeaderCSS(string cssUrl, HtmlHead htmlHeader)
        {
            string BASE_URL = HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            HtmlGenericControl Include = new HtmlGenericControl("link");
            Include.Attributes.Add("type", "text/css");
            Include.Attributes.Add("rel", "stylesheet");
            Include.Attributes.Add("href", BASE_URL + cssUrl);
            htmlHeader.Controls.Add(Include);
        }
    }
}
